package com.ddstation.chart.task;

import com.alibaba.fastjson.JSONObject;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;

import com.ddstation.crud.entity.DtInvsManageInstitutionEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionMapper;
import com.ddstation.home_page.model.NameValueModel;
import com.ddstation.hzsc_invs.autonomy_examination.service.DtInvsAutonomyExaminationInstitutionDataService;
import org.mybatis.spring.annotation.MapperScan;
import com.ddstation.chart.util.CvnDateUtil;
import com.ddstation.exam.entity.DtInvsChartInfoEntity;
import com.ddstation.exam.mapper.DtInvsChartInfoMapper;
import com.ddstation.home_page.enumerate.ChartInfoEnum;
import com.ddstation.home_page.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@MapperScan({"com.ddstation.exam.mapper","com.ddstation.crm.institution.mapper","com.ddstation.crud.mapper"})
public class ChartInfoStatisticsTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChartInfoStatisticsTask.class);

    @Resource private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
    @Resource private DtInvsChartInfoMapper dtInvsChartInfoMapper;
    @Resource private DtInvsManageInstitutionMapper dtInvsManageInstitutionMapper;
    @Resource private DtInvsAutonomyExaminationInstitutionDataService dtInvsAutonomyExaminationInstitutionDataService;

    //上城区域ID
    private static final String INVS_INSTITUTION_ID = "00000007";

    //大屏数据统计
    public void task() {
        try {
            DtInvsManageInstitutionEntity dtInvsManageInstitutionEntity = dtInvsManageInstitutionMapper.selectByPrimaryKey(INVS_INSTITUTION_ID);
            if(dtInvsManageInstitutionEntity == null) {
                return;
            }

            Integer province = Integer.valueOf(dtInvsManageInstitutionEntity.getProvince());
            Integer city = Integer.valueOf(dtInvsManageInstitutionEntity.getCity());
            Integer county = Integer.valueOf(dtInvsManageInstitutionEntity.getCounty());

            //0：今日  1：本周  2：本月
            Integer datePatten = 1;

            //综合展示
            comprehensiveDisplayStatistics(INVS_INSTITUTION_ID, province, city, county);

            //机构统查
            institutionReviewStatistics(province, city, county);

            //机构自制 => 医疗His
            saveMedicalHis(INVS_INSTITUTION_ID, datePatten, province, city, county);

            //政府监管 => 行政执法 => 诊疗行为监管
            savePrescriptionSupervision(INVS_INSTITUTION_ID, datePatten, province, city, county);

            //政府监管 => 行政执法 => 卫生消毒监督
            saveAccountSupervision(INVS_INSTITUTION_ID, datePatten, province, city, county);

            //社会监督 => 二维码监督
            qrcodeSupervisionStatistics(province, city, county);

            //综合应用
            comprehensiveApplicationStatistics(INVS_INSTITUTION_ID, province, city, county);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //机构统查
    public void institutionReviewStatistics(Integer province, Integer city, Integer county) {

        JSONObject obj = new JSONObject();

        JSONObject searchTypes = getSearchTypes(province, city, county);
        obj.put("searchTypes", searchTypes);

        //机构统查 => 机构总数
        Integer quantity = dtHealthManageInstitutionMapper.statisticsInstitutionReviewQuantity(province, city, county, null);
        obj.put("quantity", quantity);

        Integer total = dtHealthManageInstitutionMapper.statisticsInstitutionReviewTotal(province, city, county, null);
        obj.put("total", total);

        //机构统查 => 行业类型
        List<NameValueModel> typeList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewType();
        obj.put("type", typeList);

        //机构统查 => 行业
        List<HashMap> industryList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewIndustry(province, city, county);
        obj.put("industry", industryList);

        //机构统查 => 等级
        List<HashMap> levelList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewLevel(province, city, county);
        obj.put("level", levelList);

        //机构统查 => 经济性质8
        HashMap economicList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewEconomic(province, city, county);
        obj.put("economic", economicList);

        //机构统查 => 所有权性质
        List<HashMap> ownershipList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewOwnership(province, city, county, null);
        obj.put("ownership", ownershipList);

        //机构统查 => 街道分布
        List<HashMap> districtList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewDistrict(province, city, county);
        obj.put("district", districtList);

        //机构统查 => 轮播
        List<HashMap<String,Object>> carouselList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewCarousel(province, city, county);
        obj.put("carousel", carouselList);

        String data = JSONObject.toJSONString(obj);

        //保存数据
        DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
        chartInfoEntity.setData(data);
        chartInfoEntity.setId(ChartInfoEnum.INSTITUTION_REVIEW.getId());
        chartInfoEntity.setName(ChartInfoEnum.INSTITUTION_REVIEW.getName());
        dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
    }

    //机构自制 => 医疗HIS
    public void saveMedicalHis(String invsInstitutionId,Integer datePatten, Integer province, Integer city, Integer county) {

        HpCommonParModel _p = new HpCommonParModel();
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);
        _p.setInvsInstitutionId(invsInstitutionId);

        //查询数据
        MedicalHisDataModel dataModel = new MedicalHisDataModel();
        //累计病例
        Integer presCaseCount = dtHealthManageInstitutionMapper.statisticsDailyCase(_p);
        dataModel.setAllCaseCnt(presCaseCount);
        //累计处方
        int allPresCnt = dtHealthManageInstitutionMapper.statisticsDailyPrescription(_p);
        dataModel.setAllPresCnt(allPresCnt);

        String[] dateRange = CvnDateUtil.cvnDateRange(datePatten);
        _p.setDtFrom(dateRange[0]);
        _p.setDtTo(dateRange[1]);
        _p.setLimit(5);
        SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
        Calendar today = Calendar.getInstance();
        String toYm = sdf.format(today.getTime());
        today.add(Calendar.MONTH, -11);
        String fromYm = sdf.format(today.getTime());
        _p.setFromYm(fromYm);//趋势图中的年月
        _p.setToYm(toYm);//趋势图中的年月

        //累计台账
        DailyStatisticsModel allTimeDailyStatisticsActionModel = dtHealthManageInstitutionMapper.statisticsDailyAction(invsInstitutionId, null,null);
        dataModel.setAllActionCnt(allTimeDailyStatisticsActionModel.getActionDailyCount());

        //处方违规 月趋势
        Integer[] violateTypes = {40};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        HpCommonParModel _pViolate = new HpCommonParModel();//查询卫生警报用参数
        BeanUtils.copyProperties(_p, _pViolate);
        _pViolate.setBusinessTypeList(violateTypes);
        List<NameValueModel> violateTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_pViolate);
        dataModel.setViolateTimeLine(violateTimeLine);

        //卫生警告 月趋势
        Integer[] warningTypes = {10, 20, 30, 60, 110};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        HpCommonParModel _pWarings = new HpCommonParModel();//查询卫生警报用参数
        BeanUtils.copyProperties(_p, _pWarings);
        _pWarings.setBusinessTypeList(warningTypes);
        List<NameValueModel> warningTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_pWarings);
        dataModel.setWarningTimeLine(warningTimeLine);

        //诊疗行为违规机构(处方违规)
        AllPartModel illegalInstitution = dtHealthManageInstitutionMapper.statisticsAbnormalInstitution(invsInstitutionId, 1, _p.getDtFrom(), _p.getDtTo());
        dataModel.setIllegalInstitution(illegalInstitution);

        //台账异常机构
        AllPartModel abnormalInstitution = dtHealthManageInstitutionMapper.statisticsAbnormalInstitution(invsInstitutionId, 2, _p.getDtFrom(), _p.getDtTo());
        dataModel.setAbnormalInstitution(abnormalInstitution);

        //病例覆盖率
        List<NameValueModel> caseCoverage = dtHealthManageInstitutionMapper.selectCaseCoverage(_p);
        dataModel.setCaseCoverage(caseCoverage);

        //台账覆盖率
        List<NameValueModel> accountCoverage = dtHealthManageInstitutionMapper.selectAccountCoverage(_p);
        dataModel.setAccountCoverage(accountCoverage);

        //处方违规数
        List<NameValueModel> prescriptionViolation = dtHealthManageInstitutionMapper.selectPrescriptionViolation(_p, 2);
        dataModel.setPrescriptionViolation(prescriptionViolation);

        //台账类型
        HashMap accountType = dtHealthManageInstitutionMapper.selectAccountType(invsInstitutionId, null, _p.getDtFrom(), _p.getDtTo());
        dataModel.setAccountType(accountType);
        Object dataObj = JSONObject.toJSON(dataModel);

        //保存数据
        ChartInfoEnum chartInfoEnum = ChartInfoEnum.MEDICAL_HIS;
        DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
        chartInfoEntity.setData(dataObj.toString());
        chartInfoEntity.setId(chartInfoEnum.getId()+"_"+datePatten);
        chartInfoEntity.setName(chartInfoEnum.getName());
        dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
    }

    //政府监管 => 行政执法 => 诊疗行为监管
    public void savePrescriptionSupervision(String invsInstitutionId,Integer datePatten, Integer province, Integer city, Integer county) {
        int businessType = 2;//状态 1:台账: 2:处方
        String[] dateRange = CvnDateUtil.cvnDateRange(datePatten);
        HpCommonParModel _p = new HpCommonParModel();
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);
        _p.setInvsInstitutionId(invsInstitutionId);
        _p.setDtFrom(dateRange[0]);
        _p.setDtTo(dateRange[1]);
        SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
        Calendar today = Calendar.getInstance();
        String toYm = sdf.format(today.getTime());
        today.add(Calendar.MONTH, -11);
        String fromYm = sdf.format(today.getTime());
        _p.setFromYm(fromYm);//趋势图中的年月
        _p.setToYm(toYm);//趋势图中的年月
        //查询数据
        Map<String, Object> dataModel = new HashMap<>();

        JSONObject searchTypes = getSearchTypes(province, city, county);
        dataModel.put("searchTypes", searchTypes);

        //累计处方
//        int allPresCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,null, null, null, null);
        int allPresCnt = dtHealthManageInstitutionMapper.statisticsDailyPrescription(_p);
        dataModel.put("allPresCnt", allPresCnt);
        //异常处方
        int errorPresCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), null);
        dataModel.put("errorPresCnt", errorPresCnt);
        //机构总数
        int allInstCnt = dtHealthManageInstitutionMapper.countInstitution(invsInstitutionId, businessType,null, null, null);
        dataModel.put("allInstCnt", allInstCnt);
        //异常处方机构数
        int errorInstCnt = dtHealthManageInstitutionMapper.countInstitution(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("errorInstCnt", errorInstCnt);
        //处方违规 月趋势
        Integer[] violateTypes = {40};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        _p.setBusinessTypeList(violateTypes);
        //处方违规数趋势
//        List<NameValueModel> violateTimeLine = homePageMapper.selectTimeLine(_p);
        List<NameValueModel> violateTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_p);
        dataModel.put("violateTimeLine", violateTimeLine);
        //处方违规机构街道分布
        List<NameValueModel> prescriptionViolation = dtHealthManageInstitutionMapper.selectPrescriptionViolation(_p, businessType);
        dataModel.put("prescriptionViolation", prescriptionViolation);
        //处方违规机构等级
        List<NameValueModel> presViolateInstitutionByLevel = dtHealthManageInstitutionMapper.presViolateInstitutionByLevel(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByLevel", presViolateInstitutionByLevel);
        //处方违规机构行业性质
        List<NameValueModel> presViolateInstitutionByType = dtHealthManageInstitutionMapper.presViolateInstitutionByType(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByType", presViolateInstitutionByType);
        //处方违规机构经济性质
        HashMap presViolateInstitutionByAttr = dtHealthManageInstitutionMapper.presViolateInstitutionByAttr(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByAttr", presViolateInstitutionByAttr);
        //处方违规类型
//        List<HashMap> presDailyByType = dtHealthManageInstitutionMapper.presDailyByType(invsInstitutionId, _p.getDtFrom(), _p.getDtTo());
        List<HashMap> presDailyByType = dtHealthManageInstitutionMapper.getPrescriptionIllegalDistributionList(_p);
        dataModel.put("presDailyByType", presDailyByType);
        //散点图(处方异常机构)
        List<MapModel> presViolateInstitutionList = dtHealthManageInstitutionMapper.presViolateInstitution(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        for(MapModel presViolateInstitution:presViolateInstitutionList){
            String position = presViolateInstitution.getPosition();
            if(position != null){
                String[] split = position.split("\\|");
                if(split != null && split.length == 2){
                    presViolateInstitution.setLongitude(Float.parseFloat(split[0]));
                    presViolateInstitution.setLatitude(Float.parseFloat(split[1]));
                    presViolateInstitution.setPosition(null);
                }
            }
        }
        dataModel.put("presViolateInstitutionList", presViolateInstitutionList);
        Object dataObj = JSONObject.toJSON(dataModel);
        //保存数据
        DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
        ChartInfoEnum chartInfoEnum = ChartInfoEnum.PRESRCIPTION_SUPERVISION;
        chartInfoEntity.setData(dataObj.toString());
        chartInfoEntity.setId(chartInfoEnum.getId()+"_"+datePatten);
        chartInfoEntity.setName(chartInfoEnum.getName());
        dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
    }

    //政府监管 => 行政执法 => 卫生消毒监督
    public void saveAccountSupervision(String invsInstitutionId,Integer datePatten, Integer province, Integer city, Integer county) {
        int businessType = 1;//状态 1:台账: 2:处方
        String[] dateRange = CvnDateUtil.cvnDateRange(datePatten);
        HpCommonParModel _p = new HpCommonParModel();
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);
        _p.setInvsInstitutionId(invsInstitutionId);
        _p.setDtFrom(dateRange[0]);
        _p.setDtTo(dateRange[1]);
        SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
        Calendar today = Calendar.getInstance();
        String toYm = sdf.format(today.getTime());
        today.add(Calendar.MONTH, -11);
        String fromYm = sdf.format(today.getTime());
        _p.setFromYm(fromYm);//趋势图中的年月
        _p.setToYm(toYm);//趋势图中的年月
        //查询数据
        Map<String, Object> dataModel = new HashMap<>();

        JSONObject searchTypes = getSearchTypes(province, city, county);
        dataModel.put("searchTypes", searchTypes);

        //累计台账
        DailyStatisticsModel total = dtHealthManageInstitutionMapper.statisticsDailyAction(invsInstitutionId, null,null);
        dataModel.put("total", total.getActionDailyCount());

        DailyStatisticsModel allActionCnt = dtHealthManageInstitutionMapper.statisticsDailyAction(invsInstitutionId, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("allActionCnt", allActionCnt.getActionDailyCount());

        //异常台账
        int errorActionCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), null);
        dataModel.put("errorActionCnt", errorActionCnt);

        //机构总数
        int allInstCnt = dtHealthManageInstitutionMapper.countInstitution(invsInstitutionId, businessType, null, null, null);
        dataModel.put("allInstCnt", allInstCnt);

        //异常台账机构数
        int errorInstCnt = dtHealthManageInstitutionMapper.countInstitution(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("errorInstCnt", errorInstCnt);

        //账违规数趋势
        Integer[] warningTypes = {10,20,30,60,110};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        _p.setBusinessTypeList(warningTypes);
        List<NameValueModel> warningTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_p);
        dataModel.put("warningTimeLine", warningTimeLine);

        //台账违规机构等级
        List<NameValueModel> presViolateInstitutionByLevel = dtHealthManageInstitutionMapper.presViolateInstitutionByLevel(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByLevel", presViolateInstitutionByLevel);

        //台账违规机构行业性质
        List<NameValueModel> presViolateInstitutionByType = dtHealthManageInstitutionMapper.presViolateInstitutionByType(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByType", presViolateInstitutionByType);

        //台账违规机构经济性质
        HashMap presViolateInstitutionByAttr = dtHealthManageInstitutionMapper.presViolateInstitutionByAttr(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("presViolateInstitutionByAttr", presViolateInstitutionByAttr);

        //台账违规机构街道分布
        List<NameValueModel> prescriptionViolation = dtHealthManageInstitutionMapper.selectPrescriptionViolation(_p, businessType);
        dataModel.put("prescriptionViolation", prescriptionViolation);

        //台账分类统计
        HashMap accountType = dtHealthManageInstitutionMapper.selectAccountType(invsInstitutionId, -1, _p.getDtFrom(), _p.getDtTo());
        dataModel.put("accountType", accountType);

        //散点图(台账异常机构)
        List<MapModel> presViolateInstitutionList = dtHealthManageInstitutionMapper.presViolateInstitution(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        for(MapModel presViolateInstitution:presViolateInstitutionList){
            String position = presViolateInstitution.getPosition();
            if(position != null){
                String[] split = position.split("\\|");
                if(split != null && split.length == 2){
                    presViolateInstitution.setLongitude(Float.parseFloat(split[0]));
                    presViolateInstitution.setLatitude(Float.parseFloat(split[1]));
                    presViolateInstitution.setPosition(null);
                }
            }
        }
        dataModel.put("presViolateInstitutionList", presViolateInstitutionList);


        Object dataObj = JSONObject.toJSON(dataModel);
        //保存数据
        DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
        ChartInfoEnum chartInfoEnum = ChartInfoEnum.ACCOUNT_SUPERVISION;
        chartInfoEntity.setData(dataObj.toString());
        chartInfoEntity.setId(chartInfoEnum.getId()+"_"+datePatten);
        chartInfoEntity.setName(chartInfoEnum.getName());
        dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
    }

    //综合展示 时间固定不能切换 社会监督数据近一个月
    public void comprehensiveDisplayStatistics(String invsInstitutionId, Integer province, Integer city, Integer county) {

        JSONObject searchTypes = getSearchTypes(province, city, county);

        Integer quantity = dtHealthManageInstitutionMapper.statisticsInstitutionReviewQuantity(province, city, county, null);
        Integer total = dtHealthManageInstitutionMapper.statisticsInstitutionReviewTotal(province, city, county, null);

        JSONObject autonomyExamination = getAutonomyExamination(province, city, county);

        JSONObject societyVision = getSocietyVision(province, city, county);

        List<NameValueModel> qualityControlList = getQualityControl();

        List<NameValueModel> feedbackList = getFeedback();

        int[] pattens = {1};
        for (int i=0; i < pattens.length; i++)
        {
            JSONObject obj = new JSONObject();
            //综合展示 => 搜索条件
            obj.put("searchTypes", searchTypes);

            //综合展示 => 机构总数
            obj.put("total", total);
            obj.put("quantity", quantity);

            //综合展示 => 地图点
            obj.put("mapInfo", getDisplayMapInfo(province, city, county, pattens[i]));

            //综合展示 => 诊疗行为
            obj.put("prescriptionSupervision", getPrescriptionSupervisionData(invsInstitutionId, pattens[i], province, city, county));

            //综合展示 => 卫生消毒
            obj.put("accountSupervision", getAccountSupervisionData(invsInstitutionId, pattens[i], province, city, county));

            //综合展示 => 自律自查
            obj.put("autonomyExamination", autonomyExamination);

            //综合展示 => 社会监督
            obj.put("societyVision", societyVision);

            //综合展示 => 社会监督
            obj.put("qualityControl", qualityControlList);

            //综合展示 => 信用评价
            obj.put("feedback", feedbackList);

            //保存数据
            DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
            ChartInfoEnum chartInfoEnum = ChartInfoEnum.COMPREHENSIVE_DISPLAY;
            chartInfoEntity.setData(JSONObject.toJSONString(obj));
            chartInfoEntity.setId(chartInfoEnum.getId()+"_"+pattens[i]);
            chartInfoEntity.setName(chartInfoEnum.getName());
            dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
        }
    }

    //综合展示 搜索条件
    public JSONObject getSearchTypes(Integer province, Integer city, Integer county) {
        JSONObject obj = new JSONObject();

        //街道
        List<HashMap> districtList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewDistrict(province, city, county);
        obj.put("district", districtList);

        //行业
        List<HashMap> industryList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewIndustry(province, city, county);
        obj.put("industry", industryList);

        //等级
        List<HashMap> levelList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewLevel(province, city, county);
        obj.put("level", levelList);

        //经济性质
        HashMap economicList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewEconomic(province, city, county);
        obj.put("economic", economicList);

        //所有权性质8
        List<HashMap> ownershipList = dtHealthManageInstitutionMapper.statisticsInstitutionReviewOwnership(province, city, county, null);
        obj.put("ownership", ownershipList);

        return obj;
    }

    //综合应用
    public void comprehensiveApplicationStatistics(String invsInstitutionId, Integer province, Integer city, Integer county) {

        JSONObject autonomyExamination = getAutonomyExamination(province, city, county);

        JSONObject societyVision = getSocietyVision(province, city, county);

        List<NameValueModel> qualityControlList = getQualityControl();

        List<NameValueModel> feedbackList = getFeedback();

        int[] pattens = {1, 3};
        for (int i=0; i < pattens.length; i++)
        {
            JSONObject obj = new JSONObject();

            //综合应用 => 地图点
            obj.put("mapInfo", getMapInfo(invsInstitutionId, pattens[i]));

            //综合应用 => 诊疗行为
            obj.put("prescriptionSupervision", getPrescriptionSupervisionData(invsInstitutionId, pattens[i], province, city, county));

            //综合应用 => 卫生消毒
            obj.put("accountSupervision", getAccountSupervisionData(invsInstitutionId, pattens[i], province, city, county));

            //综合应用 => 自律自查
            obj.put("autonomyExamination", autonomyExamination);

            //综合应用 => 社会监督
            obj.put("societyVision", societyVision);

            //综合应用 => 社会监督
            obj.put("qualityControl", qualityControlList);

            //综合应用 => 信用评价
            obj.put("feedback", feedbackList);

            //保存数据
            DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
            ChartInfoEnum chartInfoEnum = ChartInfoEnum.COMPREHENSIVE_APPLICATION;
            chartInfoEntity.setData(JSONObject.toJSONString(obj));
            chartInfoEntity.setId(chartInfoEnum.getId()+"_"+pattens[i]);
            chartInfoEntity.setName(chartInfoEnum.getName());
            dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
        }
    }

    //综合应用 => 地图点
    public JSONObject getMapInfo(String invsInstitutionId, Integer datePatten) {
        HpCommonParModel _p = getCommonParams(datePatten);
        JSONObject obj = new JSONObject();

        //状态 1:台账: 2:处方
        int businessType = 2;
        //综合应用 => 地图点 => 处方违规
        List<MapModel> psPoints = dtHealthManageInstitutionMapper.presViolateInstitution(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        psPoints = mapInfoAnalysis(psPoints);
        obj.put("prescriptionSupervisionPoints", psPoints);

        //综合应用 => 地图点 => 台账异常
        businessType = 1;
        List<MapModel> asPoints = dtHealthManageInstitutionMapper.presViolateInstitution(invsInstitutionId, businessType, _p.getDtFrom(), _p.getDtTo());
        asPoints = mapInfoAnalysis(asPoints);
        obj.put("accountSupervisionPoints", asPoints);

        //综合应用 => 地图点 => 未完成自查
        List<MapModel> aePoints = new ArrayList<>();
        obj.put("autonomyExaminationPoints", aePoints);

        //综合应用 => 地图点 => 信用评价差
        List<MapModel> fPoints = new ArrayList<>();
        obj.put("feedbackPoints", fPoints);

        return  obj;
    }

    //综合应用 => 地图点
    public List<HashMap> getDisplayMapInfo(Integer province, Integer city, Integer county, Integer datePatten) {
        HpCommonParModel _p = getCommonParams(datePatten);
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);
        _p.setLimit(50);

        List<HashMap> mapInfo = dtHealthManageInstitutionMapper.getDisplayMapInfo(_p);

        return  mapInfo;
    }

    //综合应用 => 诊疗行为
    public JSONObject getPrescriptionSupervisionData(String invsInstitutionId, Integer datePatten, Integer province, Integer city, Integer county) {

        //状态 1:台账: 2:处方
        int businessType = 2;
        HpCommonParModel _p = getCommonParams(datePatten);
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);

        Integer[] violateTypes = {40};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        _p.setBusinessTypeList(violateTypes);

        JSONObject obj = new JSONObject();

        //诊疗行为 => 电子处方数
//        int allPresCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,null, _p.getDtFrom(), _p.getDtTo(), null);
        int allPresCnt = dtHealthManageInstitutionMapper.statisticsDailyPrescription(_p);
        obj.put("allPresCnt", allPresCnt);

        //诊疗行为 => 违规处方数
        int errorPresCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), null);
        obj.put("errorPresCnt", errorPresCnt);

        //诊疗行为 => 违规处方已处理数
        int errorPresProcessedCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), -1);
        obj.put("errorPresProcessedCnt", errorPresProcessedCnt);


        //诊疗行为 => 处方违规类型
//        List<HashMap> presDailyByType = dtHealthManageInstitutionMapper.presDailyByType(invsInstitutionId, _p.getDtFrom(), _p.getDtTo());
        List<HashMap> presDailyByType = dtHealthManageInstitutionMapper.getPrescriptionIllegalDistributionList(_p);
        obj.put("presDailyByType", presDailyByType);

        //诊疗行为 => 违规处方数趋势
//        List<NameValueModel> violateTimeLine = homePageMapper.selectTimeLine(_p);
        List<NameValueModel> violateTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_p);
        obj.put("violateTimeLine", violateTimeLine);

        return obj;
    }

    //综合应用 => 卫生消毒
    public JSONObject getAccountSupervisionData(String invsInstitutionId, Integer datePatten, Integer province, Integer city, Integer county) {

        //状态 1:台账: 2:处方
        int businessType = 1;
        HpCommonParModel _p = getCommonParams(datePatten);
        _p.setProvince(province);
        _p.setCity(city);
        _p.setCounty(county);
        JSONObject obj = new JSONObject();

        //卫生消毒 => 电子台账数
        DailyStatisticsModel allActionCnt = dtHealthManageInstitutionMapper.statisticsDailyAction(invsInstitutionId, _p.getDtFrom(), _p.getDtTo());
        obj.put("allActionCnt", allActionCnt.getActionDailyCount());

        //卫生消毒 => 异常台账数
        int errorActionCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), null);
        obj.put("errorActionCnt", errorActionCnt);

        //卫生消毒 => 异常台账数
        int errorActionProcessedCnt = dtHealthManageInstitutionMapper.countPrescriptionDaily(invsInstitutionId, businessType,-1, _p.getDtFrom(), _p.getDtTo(), null);
        obj.put("errorActionProcessedCnt", errorActionProcessedCnt);

        //台账类型
        HashMap accountType = dtHealthManageInstitutionMapper.selectAccountType(invsInstitutionId, -1, _p.getDtFrom(), _p.getDtTo());
        obj.put("accountType", accountType);

        //卫生消毒 => 异常台账数违规趋势
        Integer[] warningTypes = {10,20,30,60,110};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
        _p.setBusinessTypeList(warningTypes);
//        List<NameValueModel> warningTimeLine = homePageMapper.selectTimeLine(_p);
        List<NameValueModel> warningTimeLine = dtHealthManageInstitutionMapper.getIllegalTrendList(_p);
        obj.put("warningTimeLine", warningTimeLine);

        return obj;
    }

    //综合应用 => 自律自查
    public JSONObject getAutonomyExamination(Integer province, Integer city, Integer county) {
        JSONObject obj = new JSONObject();

        //综合应用 => 自律自查 => 应自查数
        obj.put("inspections", 0);

        int year = Integer.parseInt(DateUtil.getCurrentYear());
        int month = Integer.parseInt(DateUtil.getCurrentMonth());

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("type",0);
        params.put("province",province);
        params.put("city",city);
        params.put("county",county);
        params.put("year",year-1);
        params.put("examinationSt",1);
        int overllHaveExamination = dtInvsAutonomyExaminationInstitutionDataService.count(params);
        //综合应用 => 自律自查 => 未全面自查数
        obj.put("incompleteComprehensiveInspections", overllHaveExamination);

        int quarter = (month % 3 == 0 ? (month / 3) : (month / 3 + 1));
        //获取上个季度
        quarter--;
        //上个季度是否是去年
        if(quarter == 0){
            year--;
            quarter = 4;
        }

        params.put("type",1);
        params.put("quarter",quarter);
        params.put("year",year);
        params.put("enforcementSt",null);
        params.put("examinationSt",1);
        int dailyHaveExamination = dtInvsAutonomyExaminationInstitutionDataService.count(params);
        //综合应用 => 自律自查 => 未专业自查数
        obj.put("incompleteProfessionalInspections", dailyHaveExamination);

        return obj;
    }

    //综合应用 => 社会监督
    public JSONObject getSocietyVision(Integer province, Integer city, Integer county) {
        JSONObject obj = new JSONObject();

        //综合应用 => 社会监督 => 无扫码记录机构数
        HpCommonParModel codeParams = getCommonParams(3);
        int noQrcodeScanningCnt = dtHealthManageInstitutionMapper.countNoQrcodeScanningInstitution(province, city, county, codeParams.getDtFrom(), codeParams.getDtTo());
        obj.put("noQrcodeScanning", noQrcodeScanningCnt);

        //综合应用 => 社会监督 => 公众评价数小于3数量
        int fewPublicCommentsCnt = dtHealthManageInstitutionMapper.countFewPublicCommentsInstitution(province, city, county, 3, codeParams.getDtFrom(), codeParams.getDtTo());
        obj.put("fewPublicComments", fewPublicCommentsCnt);

        //综合应用 => 社会监督 => 满意度饼图数据
        HashMap satisfactionList = dtHealthManageInstitutionMapper.statisticsInstitutionSatisfaction(province, city, county, codeParams.getDtFrom(), codeParams.getDtTo());
        obj.put("satisfactionList", satisfactionList);

        return obj;
    }

    //综合应用 => 质控评分
    public List<NameValueModel> getQualityControl() {

        //综合应用 => 社会监督 => 满意度饼图数据
        NameValueModel nameValueModel1 = new NameValueModel();
        nameValueModel1.setName("分数≤60分");
        nameValueModel1.setValue(0);
        NameValueModel nameValueModel2 = new NameValueModel();
        nameValueModel2.setName("60分<分数<80分");
        nameValueModel2.setValue(0);
        NameValueModel nameValueModel3 = new NameValueModel();
        nameValueModel3.setName("分数≥80分");
        nameValueModel3.setValue(0);
        List<NameValueModel> scoreList = new ArrayList<>();
        scoreList.add(nameValueModel1);
        scoreList.add(nameValueModel2);
        scoreList.add(nameValueModel3);

        return scoreList;
    }

    //综合应用 => 信用评价
    public List<NameValueModel> getFeedback() {

        //综合应用 => 社会监督 => 满意度饼图数据
        NameValueModel nameValueModel1 = new NameValueModel();
        nameValueModel1.setName("优秀");
        nameValueModel1.setValue(0);
        NameValueModel nameValueModel2 = new NameValueModel();
        nameValueModel2.setName("良");
        nameValueModel2.setValue(0);
        NameValueModel nameValueModel3 = new NameValueModel();
        nameValueModel3.setName("中等");
        nameValueModel3.setValue(0);
        NameValueModel nameValueModel4 = new NameValueModel();
        nameValueModel4.setName("较差");
        nameValueModel4.setValue(0);
        NameValueModel nameValueModel5 = new NameValueModel();
        nameValueModel5.setName("差");
        nameValueModel5.setValue(0);
        List<NameValueModel> feedbackList = new ArrayList<>();
        feedbackList.add(nameValueModel1);
        feedbackList.add(nameValueModel2);
        feedbackList.add(nameValueModel3);
        feedbackList.add(nameValueModel4);
        feedbackList.add(nameValueModel5);

        return feedbackList;
    }

    //社会监督 => 二维码监督
    public void qrcodeSupervisionStatistics(Integer province, Integer city, Integer county) {
        JSONObject obj = new JSONObject();

        JSONObject searchTypes = getSearchTypes(province, city, county);
        obj.put("searchTypes", searchTypes);

        //社会监督 => 二维码监督 => 公示医疗机构数
        int publicityCnt = dtHealthManageInstitutionMapper.countPublicityInstitutions(province, city, county);
        obj.put("publicityInstitutions", publicityCnt);

        //社会监督 => 二维码监督 => 累计公众评价数
        int evaluationsCnt = dtHealthManageInstitutionMapper.countPublicEvaluations(province, city, county, null, null);
        obj.put("publicEvaluations", evaluationsCnt);

        //社会监督 => 二维码监督 => 累计二维码查询数
        int scanningCnt = dtHealthManageInstitutionMapper.countQrcodeScanning(province, city, county, null, null);
        obj.put("qrcodeScanning", evaluationsCnt);

        //社会监督 => 二维码监督 => 公众评价最高N家机构
        List<HashMap> highestInstitutionsList = dtHealthManageInstitutionMapper.statisticsInstitutionByEvaluations(province, city, county, null, null, "desc", 5);
        obj.put("highestInstitutionsList", highestInstitutionsList);

        //社会监督 => 二维码监督 => 公众评价最低N家机构
        List<HashMap> lowestInstitutionsList = dtHealthManageInstitutionMapper.statisticsInstitutionByEvaluations(province, city, county, null, null, "asc", 5);
        obj.put("lowestInstitutionsList", lowestInstitutionsList);

        //社会监督 => 二维码监督 => 公众评价满意度
        HashMap satisfactionList = dtHealthManageInstitutionMapper.statisticsInstitutionSatisfaction(province, city, county, null, null);
        obj.put("satisfactionList", satisfactionList);

        String data = JSONObject.toJSONString(obj);

        //保存数据
        DtInvsChartInfoEntity chartInfoEntity = new DtInvsChartInfoEntity();
        chartInfoEntity.setData(data);
        chartInfoEntity.setId(ChartInfoEnum.QRCODE_SUPERVISION.getId());
        chartInfoEntity.setName(ChartInfoEnum.QRCODE_SUPERVISION.getName());
        dtInvsChartInfoMapper.insertReplace(chartInfoEntity);
    }

    // 0：今日  1：本周  2：本月
    public HpCommonParModel getCommonParams(Integer datePatten) {

        String[] dateRange = CvnDateUtil.cvnDateRange(datePatten);

        HpCommonParModel hpCommonParModel = new HpCommonParModel();
        hpCommonParModel.setDtFrom(dateRange[0]);
        hpCommonParModel.setDtTo(dateRange[1]);

        SimpleDateFormat sdf= new SimpleDateFormat("yyyyMM");
        Calendar today = Calendar.getInstance();
        String toYm = sdf.format(today.getTime());
        today.add(Calendar.MONTH, -11);
        String fromYm = sdf.format(today.getTime());
        hpCommonParModel.setFromYm(fromYm);//趋势图中的年月
        hpCommonParModel.setToYm(toYm);//趋势图中的年月

        return hpCommonParModel;
    }

    //经纬度解析
    public List<MapModel> mapInfoAnalysis(List<MapModel> points) {
        for(MapModel point:points){
            String position = point.getPosition();
            if(position != null){
                String[] split = position.split("\\|");
                if(split != null && split.length == 2){
                    point.setLongitude(Float.parseFloat(split[0]));
                    point.setLatitude(Float.parseFloat(split[1]));
                    point.setPosition(null);
                }
            }
        }

        return  points;
    }

}
